import { message, Modal, Tag } from 'ant-design-vue'
import type { SpColumnsType } from '@/components/SpTable/type'
import { addDialog } from '@/components/SpDialog/index'
import ModalForm from '../form/modal.vue'
import type { FormExpose } from 'ant-design-vue/es/form/Form'
import type { JobListParamsType, JobType, JobWriteParamsType } from './model'
import {
  addJobAPI,
  changeJobStatusAPI,
  deleteJobAPI,
  getJobListAPI,
  runJobAPI,
  updateJobAPI
} from './api'

export function usePost() {
  const columns: SpColumnsType[] = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 100,
      align: 'center'
    },
    {
      title: '任务名称',
      dataIndex: 'jobName',
      width: 100,
      align: 'center'
    },
    {
      title: '任务组名',
      dataIndex: 'jobGroup',
      width: 100,
      cellRenderer: (record: JobType) => (
        <>
          <Tag>{record.jobGroup}</Tag>
        </>
      ),
      align: 'center'
    },
    {
      title: '调用目标',
      dataIndex: 'invokeTarget',
      width: 200,
      align: 'center',
      ellipsis: true
    },
    {
      title: 'cron表达式',
      dataIndex: 'cronExpression',
      width: 150,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 200,
      align: 'center',
      type: 'slot'
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      align: 'center'
    }
  ]

  // 任务列表
  const dataList = ref<JobType[]>([])
  // 请求参数
  const queryParams = ref<JobListParamsType>({
    pageNum: 1,
    pageSize: 5,
    total: 0
  })
  // 开关加载
  const switchLoading = ref<boolean[]>([])
  // 开关弹窗框
  const [modal, contextHolder] = Modal.useModal()
  // 加载状态
  const loading = ref(false)
  // 选中项
  const selectedRowKeys = ref<number[]>([])
  // 弹窗框Ref
  const modalRef = ref()

  // 获取任务列表
  function getDataList() {
    loading.value = true
    switchLoading.value = []
    getJobListAPI(queryParams.value).then((res) => {
      dataList.value = res.data.rows
      queryParams.value.total = res.data.total
      loading.value = false
      // 初始化开关加载状态
      switchLoading.value = dataList.value.map(() => false)
    })
  }

  // 打开弹窗
  function openModal(title: string, data?: JobType) {
    addDialog({
      title: `${title}任务`,
      width: '45%',
      contentRenderer: () =>
        h(ModalForm, {
          ref: modalRef,
          data
        }),
      beforeSure: function (done) {
        // 关闭弹窗
        function chores(title: string, name: string, done: Function) {
          message.success(`您${title}了任务名称为${name}的这条数据`)
          done()
          getDataList()
        }
        const form = modalRef.value.getRef() as FormExpose
        form.validate().then((res) => {
          const formData = res as JobWriteParamsType
          if (title == '编辑') {
            updateJobAPI(data?.id as number, formData).then(() => {
              chores(title, formData.jobName, done)
            })
          } else {
            addJobAPI(formData).then(() => {
              chores(title, formData.jobName, done)
            })
          }
        })
      }
    })
  }

  // 删除
  const deleteData = ({ id }: JobType) => {
    deleteJobAPI([id]).then(() => {
      message.success(`删除成功`)
      getDataList()
    })
  }

  // 批量删除
  function batchDeleteChange() {}

  // 改变任务状态
  function changeJobStatus(job: JobType, index: number) {
    switchLoading.value[index] = true
    modal.confirm({
      title: '提示',
      content: `你确定${job.status == 1 ? '启用' : '停止'}【${job.jobName}】定时任务吗？`,
      onOk() {
        changeJobStatusAPI(job.id, job.status as number)
          .then((res) => {
            if (res.data) {
              message.success(`${job.status ? '启用' : '停止'}【${job.jobName}】成功`)
            }
          })
          .finally(() => {
            switchLoading.value[index] = false
          })
      },
      onCancel() {
        job.status = !job.status as any
        switchLoading.value[index] = false
      }
    })
  }

  /**
   * 执行任务
   * @param job
   */
  function runJob(job: JobType) {
    modal.confirm({
      title: '提示',
      content: `你确定立即执行一次【${job.jobName}】定时任务吗？`,
      onOk() {
        runJobAPI(job.id).then((res) => {
          message.success(`执行【${job.jobName}】定时任务成功`)
        })
      },
      onCancel() {}
    })
  }

  // 选中项
  const onSelectChange = (keys: number[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    selectedRowKeys.value = keys
  }

  // 分页
  function paginationChange(paging: number, size: number) {
    queryParams.value.pageNum = paging
    queryParams.value.pageSize = size
    getDataList()
  }

  // 清空
  function clear() {
    queryParams.value = Object.assign({
      pageNum: 1,
      pageSize: 5
    })
    getDataList()
  }

  // 搜索
  function search() {
    queryParams.value.pageNum = 1
    getDataList()
  }

  onMounted(() => {
    getDataList()
  })

  return {
    openModal,
    deleteData,
    search,
    clear,
    batchDeleteChange,
    onSelectChange,
    paginationChange,
    changeJobStatus,
    runJob,
    dataList,
    columns,
    queryParams,
    loading,
    selectedRowKeys,
    switchLoading,
    contextHolder
  }
}
